#!/bin/bash
# 复制此文件后，记得将文件设置为可执行权限。
#例如将 第一个数字 7 表示将 startup.sh 文件属主设置为读(r-4)、写(w-2)、执行(x-1)的权限，第二个数字 5 表示将 startup.sh的所在组设置为读(4)、执行(1)的权限，第三个数字 1 表示将给其他用户设置为执行(1)的权限
# chmod 751 startup.sh

# $$	脚本运行的当前进程ID号
# $!	后台运行的最后一个进程的ID号

#在已知进程名(name)的前提下。获得进程pid信息。
#名称首字母加[]的目的是为了避免匹配到 awk 自身的进程
#ps -ef | awk '/[n]ame/{print $2}'
#最简单的方法是使用 pgrep
#pgrep -f name
#如果需要查找到 pid 之后 kill 掉该进程，还可以使用 pkill：
#pkill -f name
#如果是可执行程序的话，可以直接使用 pidof
#pidof name
# 其他方法
#ps  -ef | grep $CURR_APP_NAME |grep -v grep | grep -v PID | awk '{print $2}'|xargs kill -9


RETVAL=0
#export JRE_HOME=/usr/java/jdk1.8.0_141


#获取此脚本所在的目录位置
CURR_DIR_PATH="$(cd "$(dirname $0)/"; pwd)"
#获取目录的名称，目录名称即程序打包的名称
CURR_APP_NAME="${CURR_DIR_PATH##*/}"
#CURR_APP_NAME="cloud-eureka-server"
#组装当前服务jar文件绝对路径
CURR_APP_NAM_PATH=$CURR_DIR_PATH/$CURR_APP_NAME".jar"
#CURR_APP_NAM_PATH="/usr/local/server/cloud-eureka-server/cloud-eureka-server.jar"
#设置当前APP_PID文件路径
CURR_APP_NAME_PID=$CURR_DIR_PATH/$CURR_APP_NAME".pid"

#JVM 运行配置

#export JAVA_HOME=/usr/java/jdk1.8.0_141
#检查JAVA_HOME变量是否存在
#if [ -z $JAVA_HOME ]; then
#        echo "Error: JAVA_HOME environment variable is not set.."
#        exit 1
#fi


#export CLASS_PATH=/usr/java/jdk1.8.0_141/lib
#export PATH=$JAVA_HOME/bin:$PATH
#export PATH=$JRE_HOME/bin:$PATH

if [ -z $_RUNJAVA ]; then
   _RUNJAVA="java"
fi

#JAVA_OPTS="-Xms512m -Xmx3g -XX:MetaspaceSize=512m -XX:MaxMetaspaceSize=1g"
#JAVA_OPTS="-Xms128m -Xmx256m"
JAVA_OPTS=""


start()
{
        if [ -f $CURR_APP_NAM_PATH ];
          then
            #通过PIDFile检查服务信息,并进行相关操作(抄tomcat里面检查的脚本)
            #检测字符串长度是否为0，取反
            if [ ! -z "$CURR_APP_NAME_PID" ]; then
              if [ -f "$CURR_APP_NAME_PID" ]; then
                #检测文件是否为空（文件大小是否大于0），不为空返回 true。
                if [ -s "$CURR_APP_NAME_PID" ]; then
                  echo "Existing PID file found during start."
                  if [ -r "$CURR_APP_NAME_PID" ]; then
                    PID=`cat "$CURR_APP_NAME_PID"`
                    ps -p $PID >/dev/null 2>&1
                    #显示最后命令的退出状态。0表示没有错误，其他任何值表明有错误。
                    if [ $? -eq 0 ] ; then
                      echo "$CURR_APP_NAME appears to still be running with PID $PID. Start aborted."
                      exit 1
                    else
                      echo "Removing/clearing stale PID file."
                      rm -f "$CURR_APP_NAME_PID" >/dev/null 2>&1
                      if [ $? != 0 ]; then
                        if [ -w "$CURR_APP_NAME_PID" ]; then
                          cat /dev/null > "$CURR_APP_NAME_PID"
                        else
                          echo "Unable to remove or clear stale PID file. Start aborted."
                          exit 1
                        fi
                      fi
                    fi
                  else
                    echo "Unable to read PID file. Start aborted."
                    exit 1
                  fi
                else
                  rm -f "$CURR_APP_NAME_PID" >/dev/null 2>&1
                  if [ $? != 0 ]; then
                    if [ ! -w "$CURR_APP_NAME_PID" ]; then
                      echo "Unable to remove or write to empty PID file. Start aborted."
                      exit 1
                    fi
                  fi
                fi
              fi
            fi

            echo $"===== $CURR_APP_NAM_PATH Start running ... ====="
            #java $JAVA_OPTS -jar  $CURR_APP_NAM_PATH
            nohup $_RUNJAVA $JAVA_OPTS -jar  $CURR_APP_NAM_PATH > /dev/null 2>&1 &
            #nohup $_RUNJAVA $JAVA_OPTS -jar  $CURR_APP_NAM_PATH > $CURR_DIR_PATH/$CURR_APP_NAME.out 2>&1 &
            RETVAL=$?
            #将启动的服务的PID写入到PidFile中
            if [ ! -z "$CURR_APP_NAME_PID" ]; then
                echo $! > "$CURR_APP_NAME_PID"
            fi
            echo "===== $CURR_APP_NAM_PATH Start completed(pid:$!).  ======="
            return $RETVAL
        fi
}

status()
{
        #
        if [ ! -z "$CURR_APP_NAME_PID" ]; then
          if [ -f "$CURR_APP_NAME_PID" ]; then
            if [ -s "$CURR_APP_NAME_PID" ]; then
              #检查PidFile文件记录的进程PId所对应的进程是否存在（）。
              ##kill -0 PID  向某一进程发送一个无效的信号，如果该进程存在（能够接收信号），则$?为0，否则为1，检查此进程是否存在
              kill -0 `cat "$CURR_APP_NAME_PID"` >/dev/null 2>&1
              if [ $? -gt 0 ]; then
                echo "$CURR_APP_NAME status:PID file found but no matching process was found. Stop aborted."
                exit 1
              fi
            else
              echo "CURR_APP_NAME status:PID file is empty and has been ignored."
            fi
          else
            echo "CURR_APP_NAME status:$CURR_APP_NAME_PID was set but the specified file does not exist. Is $CURR_APP_NAME running? Stop aborted."
            exit 1
          fi
        fi

        #如PidFile 文件中没找到,则通过ps 和 grep 进程匹配
        #if [ -z $pid ]; then
        #   #pid=`ps -ef | grep '.*java.*'$CURR_APP_NAME | grep -v grep | awk '{print $2}'`
        #   echo "$CURR_APP_NAME PidFile"
        #fi

        ##kill -0 PID  向某一进程发送一个无效的信号，如果该进程存在（能够接收信号），则$?为0，否则为1，检查此进程是否存在
        kill -0 $pid >/dev/null 2>&1
        if [ $? -eq 0  ]; then
          echo "$CURR_APP_NAME is running"
        else
          echo "$CURR_APP_NAME has stopped"
        fi

        return $RETVAL
}

stop()
{
        #
        if [ ! -z "$CURR_APP_NAME_PID" ]; then
          if [ -f "$CURR_APP_NAME_PID" ]; then
            if [ -s "$CURR_APP_NAME_PID" ]; then
              #检查PidFile文件记录的进程PId所对应的进程是否存在（）。
              ##kill -0 PID  向某一进程发送一个无效的信号，如果该进程存在（能够接收信号），则$?为0，否则为1，检查此进程是否存在
              kill -0 `cat "$CURR_APP_NAME_PID"` >/dev/null 2>&1
              if [ $? -gt 0 ]; then
                echo "CURR_APP_NAME stop:PID file found but no matching process was found. Stop aborted."
                exit 1
              fi
            else
              echo "CURR_APP_NAME stop:PID file is empty and has been ignored."
            fi
          else
            echo "CURR_APP_NAME stop:$CURR_APP_NAME_PID was set but the specified file does not exist. Is $CURR_APP_NAME running? Stop aborted."
            exit 1
          fi
        fi

        ##如PidFile 文件中没找到,则通过ps 和 grep 进程匹配
        #if [ -z $pid ] ; then
        #      pid=`ps -ef | grep '.*java.*'$CURR_APP_NAME | grep -v grep | awk '{print $2}'`
        #fi

        #检查最终是否活动进程pid
        if [ -z $pid ] ; then
              echo "$CURR_APP_NAME no matching process was found. Stop aborted."
              exit 0
        fi

        # 检查是否获取的PId是否正常
        # ( -n  检测字符串长度是否为0，不为0返回 true。)
        if [ -n "$pid" ]
        then
           echo "kill $CURR_APP_NAM_PATH process(pid:$pid)."

           #此命令无法关掉进程
           #kill -s QUIT $pid
           #RETVAL=$?

           kill -15 $pid >/dev/null 2>&1
           RETVAL=$?

           echo -n "Closing, please wait "
           #检查进程是否关闭（抄tomcat的脚本)
           #最多等待5秒
           SLEEP=5
           FORCE=0
           if [ ! -z "$CURR_APP_NAME_PID" ]; then
             if [ -f "$CURR_APP_NAME_PID" ]; then
               while [ $SLEEP -ge 0 ]; do
                 echo -n "."
                 kill -0 $pid >/dev/null 2>&1
                 if [ $? -gt 0 ]; then
                   #换行
                   echo ""
                   #RETVAL = 0
                   rm -f "$CURR_APP_NAME_PID" >/dev/null 2>&1
                   if [ $? != 0 ]; then
                     if [ -w "$CURR_APP_NAME_PID" ]; then
                       cat /dev/null > "$CURR_APP_NAME_PID"
                       # If APP has stopped don't try and force a stop with an empty PID file
                       FORCE=0
                     else
                       echo "The PID file could not be removed or cleared."
                     fi
                   fi
                   echo "$CURR_APP_NAME stopped."
                   break
                 fi
                 if [ $SLEEP -gt 0 ]; then
                   sleep 1
                 fi
                 if [ $SLEEP -eq 0 ]; then
                   if [ $FORCE -eq 0 ]; then
                     echo "$CURR_APP_NAME did not stop in time. PID file was not removed. To aid diagnostics a thread dump has been written to standard out."
                     kill -3 $pid
                   fi
                 fi
                 SLEEP=`expr $SLEEP - 1 `
               done
             fi
           fi

           #换行
           echo ""
           return $RETVAL
        fi
}

case "$1" in
 start)
        start
        ;;
 status)
        status
        ;;
 stop)
        stop
        ;;

 restart)
         echo "Restaring $CURR_APP_NAM_PATH ..."
         $0 stop
         sleep 1
         $0 start
         ;;
 *)
        echo "Usage: $0 {start|status|stop|restart}"
        exit 1
        ;;
esac
exit $RETVAL